package com.lagou.eduauthorityboot.controller;


import com.alibaba.fastjson.JSON;


import com.lagou.eduauthorityboot.entity.*;
import com.lagou.eduauthorityboot.service.UserService;
import com.lagou.eduauthorityboot.tools.HttpClientUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping("user")
@CrossOrigin
public class WxloginController {


    @Autowired
    private UserService userService;

    private UserDTO userDTO = null;

    @GetMapping("wxlogin")
    public UserDTO wxlogin(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //1.微信官方给我们一个凭证
        String code = request.getParameter ("code");
        System.out.println ("临时凭证code：" + code);
        // 2.通过code获取access_token，定义获取access_token的url
        String getTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token? appid=wxd99431bbff8305a0&secret=60f78681d063590a469f1b297feff3c4&code="+code+"&grant_type=authorization_code";
        // 3.发请求并获得access_token
        String access_token = HttpClientUtil.doGet (getTokenUrl);
        //将json格式的token字符串转换成实体对象，方便存取
        Token tokey = JSON.parseObject (access_token, Token.class);
        //3.通过token，去微信官方获取用户的信息
        String getUserByToken_url = "https://api.weixin.qq.com/sns/userinfo? access_token=" + tokey.getAccess_token() + "&openid=" + tokey.getOpenid();
        String userinfoString = HttpClientUtil.doGet (getUserByToken_url);
        System.out.println ("userinfoString :" + userinfoString );
        // 将json格式的user字符串转换成实体对象，方便存和取
        WxUser wxUser = JSON.parseObject (userinfoString, WxUser.class);
        System.out.println("微信昵称 = " + wxUser.getNickname());
        System.out.println("微信头像 = " + wxUser.getHeadimgurl());

        //拉勾的业务流程

        //return "user/login?phone=" + wxUser.getUnionid ()  + "&password=" + wxUser.getUnionid () + "&nickname=" + wxUser.getNickname () + "&headimg=" + wxUser.getHeadimgurl ();

        //检测手机号是否注册
        UserDTO dto = userService.login (wxUser.getUnionid (), wxUser.getUnionid ());
        if (dto.getState () == EduConstant.ERROR_NOT_FOUND_PHONE_CODE) {
            //未注册，自动注册
            userService.register (wxUser.getUnionid (), wxUser.getUnionid (),wxUser.getNickname (),wxUser.getHeadimgurl ());
            //再登录
            dto = userService.login (wxUser.getUnionid (), wxUser.getUnionid ());
        }



        response.sendRedirect("http://localhost:8080/#/?token="+ dto.getToken());

        return dto;
    }


}
